package com.lin.controller;


import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

@RequestMapping("/demo1")
@Controller
public class HelloController {

    @Value("${queue.hello_queue_name}")
    private  String QUEUE_NAME;


    /*
        url: localhost:8080/demo1/sendHello
     */
    @RequestMapping("/sendHello")
    @ResponseBody
    public String sendHello() {
        //1.获取连接
        //2.发送消息到队列中去
        //*!: 注意这里使用try-with-resource来帮助我们自动关闭连接---mq客服端实现了closable接口---支持自动关闭
        try (Connection connection = RabbitUtil.getConnection();
             Channel channel = connection.createChannel();
        ) {
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            String message = "Hello from LinYuan";
            channel.basicPublish("",QUEUE_NAME,null,message.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "成功发送hello到消息队列";
    }
}
